import { effectKey, Attribute_base, LogType, SkillType, qualityName, quality, attackKey } from "../../../shared/face/enums";
import skData from '../config/skData';
import EffectManage from './EffectManage';
import type { Skill, Buff } from "../types";
import { BuffConfig } from "../types";
import BattleLogger from '../BattleLogger';
import BuffManager from './BuffManager';
import { Icard2 } from '../../tool/Icard2';
import gameCfg from '../../../gameCfg';
import { dynamicSkillDescription } from './DynamicSkillDescription';

// 重新定义_Skill接口，避免与skData中的冲突
export interface _SkillConfig extends Omit<Skill, 'effect' | 'triggerConditionConfig'> {
  effect: string[];
  triggerConditionConfig?: any; // 配置化的触发条件
}

class SkillManager {
  private skills: Map<string, Skill> = new Map();
  constructor() {
    // this.loadSkillsFromFile();
  }
  init() {
    this.loadSkillsFromFile();

    // 注册技能描述模板
    const { registerSkillDescriptionTemplates } = require('./SkillDescriptionTemplates');
    registerSkillDescriptionTemplates();
  }

  private loadSkillsFromFile() {
    BattleLogger.log('info', '开始加载技能', { skillCount: skData.length });

    skData.forEach((skill: any) => {
      try {
        this.checkSkill(skill);
        // 计算技能品质，但不修改原始技能
        const calculatedQuality = this.coverSkillquality(skill);

        const skillWithEffect = {
          ...skill,
          effect: (attacker: any, target: any, self: any, stackCount: any, index: any) => {
            try {
              if (attacker.isDie() || target.isDie()) {
                BattleLogger.log('info', '有一方已经死亡，故无法触发自身效果', {
                  attackerId: attacker.id,
                  targetId: target.id,
                  skillId: skill.id
                });
                return;
              }

              // 处理技能配置的buff
              if (skill.buffs && skill.buffs.length > 0) {
                skill.buffs.forEach((buffConfig: BuffConfig) => {
                  BuffManager.applyBuffConfig(target, buffConfig, attacker, skill.data?.[index] || {});
                });
              }

              // 创建技能数据的副本，避免修改原始配置
              let _skillData = skill.data[index] ? { ...skill.data[index] } : {};

              if (attacker.isDie() || target.isDie()) {
                BattleLogger.log('info', '有一方已经死亡，故无法触发自身效果', {
                  attackerId: attacker.id,
                  targetId: target.id,
                  skillId: skill.id
                });
                return;
              }
              let effKey = skill.effect[index];

              // 支持两种buff添加方式：旧的 '添加buff-xxx' 和新的 'addBuff:xxx'
              if (effKey.startsWith('添加buff-')) {
                _skillData.addBuffName = effKey.split('-')[1];
                effKey = '添加buff';
              } else if (effKey.startsWith('addBuff:')) {
                _skillData.addBuffName = effKey.split(':')[1];
                effKey = '添加buff';
              }

              // 获取技能使用数据（从攻击者身上）
              const skillUseData = attacker.getSkillUseData?.(skill.id);
              if (skillUseData) {
                // 应用技能等级和永久提升，获取修改后的数据副本
                _skillData = this.applySkillModifiers(_skillData, skillUseData, skill.id);
              }

              // 处理技能配置中的永久提升
              if (_skillData.permanentBoost) {
                this.handlePermanentBoost(attacker, skill.id, _skillData.permanentBoost);
              }

              BattleLogger.log('info', '执行技能效果', {
                skillId: skill.id,
                skillName: skill.name,
                effect: effKey,
                targetId: target.id
              });

              const effectFunction = EffectManage.getEffect(effKey);
              if (effectFunction) {
                effectFunction(attacker, target, self, stackCount, index, _skillData);
              } else {
                console.error(`技能效果不存在: ${effKey}, 技能: ${skill.id} - ${skill.name}`);
                debugger;
              }
            } catch (error) {
              console.error(`执行技能效果失败: ${skill.id} - ${skill.name}`, error);
            }
          }
        };

        this.addSkill(skillWithEffect);
        BattleLogger.log('info', '成功加载技能', {
          skillId: skill.id,
          skillName: skill.name,
          skillType: skill.type
        });

      } catch (error) {
        console.error(`加载技能失败: ${skill.id} - ${skill.name}`, error);
      }
    });

    BattleLogger.log('info', '技能加载完成', { loadedCount: this.skills.size });
  }
  coverAttkKey(atKey: attackKey) {
    let logType = LogType.伤害;
    switch (atKey) {
      case attackKey.普通攻击:
        logType = LogType.伤害;
        break;
      case attackKey.物理攻击:
        logType = LogType.伤害;
        break;
      case attackKey.魔法攻击:
        logType = LogType.伤害;
        break;
      case attackKey.恢复生命:
        logType = LogType.治疗;
        break;
      case attackKey.护盾:
        logType = LogType.护盾;
        break;
      case attackKey.真实攻击:
        logType = LogType.伤害;
        break;
      default:
        logType = LogType.伤害;
        console.log('没有找到攻击类型', atKey);
        process.exit(0);
        break;
    }
    return logType;
  }
  private checkSkill(skill: any) {
    if (skill.effect.length == 0) {
      console.error('技能效果为空', skill.id);
      debugger;
    }
    if (skill.effect.length != skill.data.length) {
      console.error('技能效果数量与数据数量不一致', skill.id);
      debugger;
    }
    if (skill.targetType.length != skill.effect.length) {
      console.error('技能目标类型数量与技能范围数量不一致', skill.id);
      debugger;
    }
  }

  private coverSkillquality(skill: any) {
    let baseQuality = skill.quality;
    let calculatedQuality: number;

    switch (skill.type) {
      case SkillType.主动技能:
        calculatedQuality = Math.min(skill.effect.length + baseQuality, quality.SSR);
        break;
      case SkillType.被动技能:
        calculatedQuality = Math.min(Math.ceil(skill.effect.length * 1.5) + baseQuality, quality.SSR);
        break;
      case SkillType.光环技能:
        calculatedQuality = Math.min(Math.ceil(skill.effect.length * 2) + baseQuality, quality.SSR);
        break;
      default:
        calculatedQuality = baseQuality;
    }

    // 返回计算后的品质，而不是直接修改原始技能
    return calculatedQuality;
  }
  randomSk_shop(quality: quality) {
    const availableSkills = Array.from(this.skills.values())
      .filter(skill => skill.quality >= quality);
    const randomSkill = availableSkills[Math.floor(Math.random() * availableSkills.length)];
    return randomSkill;
  }

  addSkill(skill: Skill) {
    // 创建技能数据的副本，避免修改原始配置
    const skillCopy = { ...skill };
    if (!skillCopy.data) {
      skillCopy.data = [];
    }
    this.skills.set(skill.id, skillCopy);
  }

  getSkillById(id: string): Skill | undefined {
    let skill = this.skills.get(id);
    if (!skill) {
      return;
    }
    return skill;
  }
  client_data(id: string, card: Icard2, caster?: any) {
    let skill = this.getSkillById(id);
    if (!skill) {
      return;
    }

    // 使用动态描述系统生成描述

    card.icon(gameCfg.defaultIcon, gameCfg.defaultIcon);
    
    // 优先使用desc字段，然后是reName，最后是默认名称
    let displayName = skill.name;
    let displayDesc = '';
    if (caster) {
      const skillUseData = caster.getSkillUseData?.(id);
      if (skillUseData) {
        if (skillUseData.desc) {
          displayDesc = skillUseData.desc;
        }
        if (skillUseData.reName) {
          displayName = skillUseData.reName;
        }
        card.l('等级', `Lv.${skillUseData.level}`);
      }
    }
    const dynamicDesc = this.generateDescription(skill, caster, displayDesc);

    card.l('名称', displayName);
    card.l('品质', Object.values(qualityName)[skill.quality]);
    card.l('类型', skill.type);
    card.l('分类', skill.classType);
    card.l('描述', dynamicDesc);
    card.l('冷却', skill.cooldown);
    return card;
  }
  generateDescription(skill: Skill, caster?: any, desc?: string) {
    let _desc = desc || '';
    const dynamicDesc = dynamicSkillDescription.generateDescription(skill, caster);
    return _desc + dynamicDesc;
  }

  /**
   * 应用技能修饰符（等级和永久提升）
   * @param skillData 技能数据
   * @param skillUseData 技能使用数据
   * @param skillId 技能ID
   * @returns 修改后的技能数据副本，不修改原始数据
   */
  private applySkillModifiers(skillData: any, skillUseData: any, skillId: string): any {
    if (!skillUseData) return skillData;

    const level = skillUseData.level || 1;
    const permanentBoosts = skillUseData.permanentBoosts || {};

    // 创建技能数据的深拷贝，避免修改原始配置
    const modifiedSkillData = JSON.parse(JSON.stringify(skillData));

    // 所有技能都应用等级加成
    const levelMultiplier = 1 + (level - 1) * 0.1;

    // 应用等级加成到伤害相关属性
    if (modifiedSkillData.attRange) {
      modifiedSkillData.attRange *= levelMultiplier;
    }
    if (modifiedSkillData.fixed) {
      modifiedSkillData.fixed *= levelMultiplier;
    }

    // 应用永久提升
    if (permanentBoosts.damage) {
      modifiedSkillData.fixed = (modifiedSkillData.fixed || 0) + permanentBoosts.damage;
    }
    if (permanentBoosts.attRange) {
      modifiedSkillData.attRange = (modifiedSkillData.attRange || 1) + permanentBoosts.attRange;
    }
    if (permanentBoosts.cooldown) {
      modifiedSkillData.cooldown = Math.max(0, (modifiedSkillData.cooldown || 0) - permanentBoosts.cooldown);
    }

    BattleLogger.log('info', '应用技能修饰符', {
      skillId,
      level,
      levelMultiplier,
      permanentBoosts,
      finalData: modifiedSkillData
    });

    return modifiedSkillData;
  }

  /**
   * 处理技能永久提升
   * @param attacker 攻击者
   * @param skillId 技能ID
   * @param permanentBoost 永久提升配置
   * @param battleContext 战斗上下文（可选，用于条件判断）
   */
  private handlePermanentBoost(attacker: any, skillId: string, permanentBoost: any, battleContext?: any) {
    if (!permanentBoost || !permanentBoost.type || permanentBoost.amount === undefined) {
      return;
    }

    // 检查触发条件
    if (!this.checkPermanentBoostCondition(permanentBoost, battleContext)) {
      return;
    }

    // 使用技能并记录永久提升
    const result = attacker.useSkillWithPermanentBoost?.(
      skillId,
      permanentBoost.type,
      permanentBoost.amount
    );

    if (result?.success) {
      BattleLogger.log('info', '技能永久提升', {
        skillId,
        boostType: permanentBoost.type,
        boostAmount: permanentBoost.amount,
        condition: permanentBoost.condition,
        message: result.message
      });
    }
  }

  /**
   * 检查永久提升触发条件
   * @param permanentBoost 永久提升配置
   * @param battleContext 战斗上下文
   * @returns 是否满足触发条件
   */
  private checkPermanentBoostCondition(permanentBoost: any, battleContext?: any): boolean {
    const condition = permanentBoost.condition || 'always';
    const params = permanentBoost.conditionParams || {};

    switch (condition) {
      case 'always':
        return true;

      case 'kill':
        return this.checkKillCondition(battleContext, params);

      case 'critical':
        return this.checkCriticalCondition(battleContext, params);

      case 'dodge':
        return this.checkDodgeCondition(battleContext, params);

      case 'damage_threshold':
        return this.checkDamageThresholdCondition(battleContext, params);

      case 'health_threshold':
        return this.checkHealthThresholdCondition(battleContext, params);

      case 'combo':
        return this.checkComboCondition(battleContext, params);

      default:
        BattleLogger.log('error', '未知的永久提升条件', { condition });
        return false;
    }
  }

  /**
   * 检查击杀条件
   */
  private checkKillCondition(battleContext: any, params: any): boolean {
    if (!battleContext || !battleContext.target) return false;

    // 检查目标是否死亡
    const targetDead = battleContext.target.isDead?.() || battleContext.target.health <= 0;

    // 检查目标类型
    if (params.targetType) {
      const targetType = battleContext.target.type || 'enemy';
      if (targetType !== params.targetType) return false;
    }

    return targetDead;
  }

  /**
   * 检查暴击条件
   */
  private checkCriticalCondition(battleContext: any, params: any): boolean {
    if (!battleContext) return false;

    const isCritical = battleContext.isCritical || battleContext.criticalHit;
    return isCritical === true;
  }

  /**
   * 检查闪避条件
   */
  private checkDodgeCondition(battleContext: any, params: any): boolean {
    if (!battleContext) return false;

    const isDodge = battleContext.isDodge || battleContext.dodged;
    return isDodge === true;
  }

  /**
   * 检查伤害阈值条件
   */
  private checkDamageThresholdCondition(battleContext: any, params: any): boolean {
    if (!battleContext || !battleContext.damage) return false;

    const minDamage = params.minDamage || 0;
    const maxDamage = params.maxDamage || Infinity;

    return battleContext.damage >= minDamage && battleContext.damage <= maxDamage;
  }

  /**
   * 检查生命值阈值条件
   */
  private checkHealthThresholdCondition(battleContext: any, params: any): boolean {
    if (!battleContext || !battleContext.attacker) return false;

    const healthPercent = battleContext.attacker.health / battleContext.attacker.maxHealth;
    const minHealth = params.minHealthPercent || 0;
    const maxHealth = params.maxHealthPercent || 1;

    return healthPercent >= minHealth && healthPercent <= maxHealth;
  }

  /**
   * 检查连击条件
   */
  private checkComboCondition(battleContext: any, params: any): boolean {
    if (!battleContext || !battleContext.attacker) return false;

    const minCombo = params.minCombo || 1;
    const currentCombo = battleContext.attacker.combo || 0;

    return currentCombo >= minCombo;
  }
}
export default new SkillManager();